<template>
	<i-drawer v-model="showDel" title="你确认要删除该商品吗？" confirm_title="删除" @confirm="confirm"></i-drawer>
	<i-picker :value="valueData" @confirm="pickerChange" :list="[selectData]" v-model="showPicker"></i-picker>
	<view class="add_shop">
		<view class="form">
			<i-formItem :require="true" title="业务类型" :contStyle="businessStr && !disabledEdit ? 'color: #16161F' : ''"
				:content="businessStr || '请选择业务类型'" :right="true" @click="showpick">
			</i-formItem>
			<i-formItem require="true" title="商品名称">
				<input placeholder-class="placeholder-class" @input="changeName" maxlength="20" :disabled="disabledEdit"
					v-model="formData.serviceName" type="text" placeholder="请输入商品名称（4-20个字）">
			</i-formItem>
			<i-scrollList @more="more" :noData="false" height="460rpx" :pageTotal="shopNameData.list.length"
				v-if="formData.businessType && shopNameData.list.length" :total="shopNameData.total">
				<view class="shop_item" v-for="item in shopNameData.list" :key="item.id" @click="selectName(item)">
					{{item.serviceName}}
				</view>
			</i-scrollList>
			<view v-if="formData.businessType && shopNameData.list.length"
				style="height: 1rpx; background-color: #f3f4f5"></view>
			<i-formItem require="true" title="价格">
				<input placeholder-class="placeholder-class" :disabled="disabledEdit" v-model="formData.discountPrice"
					@input="changeDiscount" type="decimal" placeholder="请输入商品价格">
			</i-formItem>
			<!-- <view class="text" v-if="formData.discountPrice>0">*平台结算价 {{formData.finalPrice}} 元</view> -->
			<i-formItem require="true" title="原价">
				<input placeholder-class="placeholder-class" :disabled="disabledEdit" v-model="formData.price"
					type="decimal" placeholder="请输入原价">
			</i-formItem>
			<view class="text" v-if="formData.discountPrice>0 && !goodsId">*最高不可超过 {{maxPrice}} 元</view>
			<view class="message">
				1. 平台手续费 1% <br />
				2. 商品原价可输入价格的1.13-10倍之间，如用户未使用优惠金抵扣，则使用原价支付
			</view>
		</view>
		<view class="lines"></view>
		<view class="form">
			<i-formItem title="排序(选填)">
				<input v-model="formData.sort" type="number" placeholder="请输入排序">
			</i-formItem>
			<view class="text" style="margin-bottom: 0;">*排序值越小，排名越靠前</view>
			<i-formItem title="是否上架">
				<switch :checked="formData.status === '0'" @change="chekChange" color="#FB652E"
					style="transform:scale(0.9)" />
				<!-- v-model="formData.sort" type="number" placeholder="请输入排序"> -->
			</i-formItem>
			<view style="height: 60rpx;"></view>
			<i-buttons v-if="!goodsId" :disabled="disabled" radius="4" padding="18rpx 0" size="32" color="#fff"
				bgColor="#FB652E" @click="add">立即添加
			</i-buttons>
			<view class="buttons" v-else>
				<i-buttons radius="4" padding="18rpx 76rpx" size="32" color="#fff" bgColor="#FB652E" @click="edit">保存
				</i-buttons>
				<view style="height: 32rpx;"></view>
				<i-buttons border="#fff" radius="4" padding="18rpx 76rpx" size="32" color="#5C6D80"
					@click="showDel = true ">删除</i-buttons>
			</view>
		</view>
	</view>
</template>

<script lang="ts" setup>
	import {
		computed,
		reactive,
		ref,
		watch
	} from 'vue';
	import {
		onLoad,
		onReady
	} from '@dcloudio/uni-app'
	import useStore from '../../stores/index'
	import {
		fixed,
		navTo,
		showTost
	} from '../../utils/common'
	import {
		addGoods,
		getMerGoodsById,
		editGoods,
		editGoodsStatus,
		getQuickGoodsName
	} from '../../api/shopping'
	import {
		getclerkDetail
	} from '../../api/user'

	import {
		getMeBusinessTypes,
		getLocalMeBusinessTypes
	} from '../../api/store'
	import {
		decimalReg
	} from '../../utils/regs'

	const showDel = ref(false)
	const disabledEdit = ref(false)
	const valueData = ref<any>([])

	const showPicker = ref(false)
	const disabled = ref(true)
	const goodsId = ref('')
	const selectData = ref([])
	const minPrice = ref(0)
	const maxPrice = ref(0)
	const ones = ref(true)
	const businessStr = ref('')
	const shopNameData = reactive({
		tyjPageNum: 1,
		tyjPageSize: 15,
		total: 0,
		list: []
	})
	const formData = reactive({
		"businessType": '',
		"discountPrice": '',
		"finalPrice": null,
		"price": 0,
		"serviceName": '',
		"sort": '',
		'status': '0'
	})
	const store = useStore()
	const userData = reactive({
		endMarketRate: 0,
		startMarketRate: 0,
		storeRate: 0
	})

	const storeInfo = computed(() => {
		return store.storeInfo
	})
	const userInfo = computed(() => {
		return store.userInfo
	})
	onLoad(async (option) => {
		if (option && option.goodsId) {
			goodsId.value = option.goodsId
		}
		if (userInfo.value.isClerk === 1) {
			const { data } = await getclerkDetail({
				userId: userInfo.value.userId
			})
			userData.startMarketRate = data.startMarketRate
			userData.endMarketRate = data.endMarketRate
			userData.storeRate = data.storeRate
		}
		if (option && option.goodsId) {
			getData(option.businessType, option.goodsId)
		}
		getStoreData()
		formData.businessType = option.businessType
	})
	onReady(() => {
		uni.setNavigationBarTitle({
			title: goodsId.value ? '编辑商品' : '添加商品'
		})
	})

	const chekChange = (e : { detail : { value : boolean } }) => {
		console.log(e.detail.value, 'e.detail.value');
		if (e.detail.value) {
			formData.status = '0'
		} else {
			formData.status = '1'
		}
	}

	const showpick = () => {
		if (disabledEdit.value) {
			return
		}
		showPicker.value = true
	}

	const pickerChange = (data : any) => {
		valueData.value = data
		formData.businessType = data[0].value
		businessStr.value = data[0].label
		shopNameData.list = []
		shopNameData.total = 0
		shopNameData.tyjPageNum = 1
		getqShopName()
	}
	const changeDiscount = (e : {
		detail : {
			value : number
		}
	}) => {
		formData.finalPrice = fixed(Number(e.detail.value) * storeInfo.value.storeRate || userData.storeRate, 2)
		maxPrice.value = fixed(Number(e.detail.value) * (storeInfo.value.endMarketRate || userData.endMarketRate), 2)
		minPrice.value = fixed(Number(e.detail.value) * (storeInfo.value.startMarketRate || userData.startMarketRate), 2)
	}

	const add = async () => {
		if (!decimalReg.test(formData.discountPrice)) {
			showTost('请输入正确会员价')
			return
		}

		if (formData.price > maxPrice.value || formData.price < minPrice.value) {
			showTost(`原价在${minPrice.value}-${maxPrice.value}之间`)
			return
		}
		if (!decimalReg.test(formData.price + '')) {
			showTost('请输入正确原价')
			return
		}

		if (formData.serviceName.length < 4) {
			showTost('商品名称在4-20个字')
			return
		}
		disabled.value = true

		try {
			await addGoods(formData)
			showTost('添加成功', () => {
				navTo('', 'navigateBack')
				disabled.value = false
			})
		} catch (e) {
			disabled.value = false
		}
	}
	const edit = async () => {
		if (!decimalReg.test(formData.discountPrice)) {
			showTost('请输入正确会员价')
			return
		}

		if (formData.price > maxPrice.value || formData.price < minPrice.value) {
			showTost(`原价在${minPrice.value}-${maxPrice.value}之间`)
			return
		}
		if (!decimalReg.test(formData.price + '')) {
			showTost('请输入正确原价')
			return
		}

		if (formData.serviceName.length < 4) {
			showTost('商品名称在4-20个字')
			return
		}
		await editGoods({
			goodsId: goodsId.value,
			"businessType": formData.businessType,
			"discountPrice": Number(formData.discountPrice),
			"finalPrice": formData.finalPrice,
			"price": formData.price,
			"serviceName": formData.serviceName,
			"sort": formData.sort,
			"status": formData.status
		})
		showTost('商品修改成功', () => {
			navTo('', 'navigateBack')
		})
	}


	const confirm = () => {
		editGoodsStatus({
			goodsId: goodsId.value,
			businessType: formData.businessType,
			status: 1,
			"type": 0
		})
		showTost('删除商品成功', () => {
			navTo('', 'navigateBack')
		})
	}

	const getStoreData = async () => {
		const { data } = storeInfo.value.merType === '0'? await getMeBusinessTypes(): await getLocalMeBusinessTypes()
		selectData.value = data.map((item : { businessType : string, businessTypeLabel : string }) => {
			return {
				label: item.businessTypeLabel,
				value: item.businessType
			}
		}).filter(i => storeInfo.value.merType === '0'? i.value !== '10003007':storeInfo.value.businessType === i.value)
		valueData.value = selectData.value.filter(item => item.value === formData.businessType)
		businessStr.value = valueData.value[0].label
		if (ones.value && goodsId.value) {
			ones.value = false
			return
		}
		getqShopName()
	}

	const getData = async (businessType : string, goodsId : string) => {
		const {
			data
		} = await getMerGoodsById({
			businessType,
			goodsId
		})
		formData.price = data.price
		formData.discountPrice = data.discountPrice
		formData.finalPrice = data.finalPrice
		formData.serviceName = data.serviceName
		formData.businessType = data.businessType
		formData.sort = data.sort
		formData.status = data.status
		businessStr.value = data.businessTypeLabel
		valueData.value = [{
			label: data.businessTypeLabel,
			value: data.businessType
		}]
		maxPrice.value = fixed(Number(data.discountPrice) * (storeInfo.value.endMarketRate || userData.endMarketRate), 2)
		minPrice.value = fixed(Number(data.discountPrice) * (storeInfo.value.startMarketRate || userData.startMarketRate), 2)
	}
	const more = () => {
		shopNameData.tyjPageNum++
		getqShopName()
	}
	const selectName = (item : { serviceName : string }) => {
		formData.serviceName = item.serviceName
		shopNameData.list = []
		shopNameData.total = 0
		shopNameData.tyjPageNum = 1
	}

	const changeName = (e : { detail : { value : string } }) => {
		if (!formData.businessType) {
			return
		}
		shopNameData.list = []
		shopNameData.total = 0
		shopNameData.tyjPageNum = 1
		getqShopName()
	}
	const getqShopName = async () => {
		const data = await getQuickGoodsName({
			"businessType": formData.businessType,
			"serviceName": formData.serviceName,
			"tyjPageNum": shopNameData.tyjPageNum,
			"tyjPageSize": shopNameData.tyjPageSize
		})
		shopNameData.list = shopNameData.list.concat(data.rows)
		shopNameData.total = data.total
	}
	watch(formData, (val) => {
		if (formData.price && formData.discountPrice && formData.serviceName && formData.businessType && formData.price > 0 && Number(formData.discountPrice) > 0) {
			disabled.value = false
		} else {
			disabled.value = true
		}
	})
</script>

<style lang="scss" scoped>
	.add_shop {
		width: 100%;
		height: 100vh;
		overflow-y: auto;

		.form {
			width: calc(100% - 64rpx);
			margin: 0 auto;
		}

		.text {
			margin-top: 20rpx;
			@include dfont(24rpx);
			color: #A0A0AD;
			margin-bottom: 40rpx;
		}

		.message {
			@include dfont(26rpx);
			color: #8E8E93;
			margin-bottom: 40rpx;
			line-height: 48rpx;
			margin-top: 12rpx;
		}

		.lines {
			height: 16rpx;
			background: $background-color;
		}

		input {
			width: 70%;
		}

		.formItems {
			@include dfont;
			color: #A0A0AD;
			width: 70%;
			@include flexRS;
		}

		.buttons {
			@include flexC;
			width: 100%;
		}

		.shop_item {
			@include flexRC;
			padding: 18rpx 0;
			@include dfont(26rpx);
			color: #A0A0AD;
		}
	}
</style>